package servlets;

import com.google.gson.Gson;
import entity.ResponseData;
import entity.Student;
import utils.DBUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/students", "/students/*"})
public class StudentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        handleCors(response);
        response.setContentType("application/json;charset=UTF-8");

        String pathInfo = request.getPathInfo();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtils.getConnection();

            if (pathInfo == null || pathInfo.equals("/")) {
                // 获取所有学生列表
                String sql = "SELECT * FROM t_student";
                pstmt = conn.prepareStatement(sql);
                rs = pstmt.executeQuery();

                List<Student> students = new ArrayList<>();
                while (rs.next()) {
                    Student student = new Student(
                            rs.getInt("studentId"),
                            rs.getString("name"),
                            rs.getString("dormBuildName"),
                            rs.getString("dormName"),
                            rs.getString("sex")
                    );
                    students.add(student);
                }

                Gson gson = new Gson();
                String jsonResponse = gson.toJson(students);
                response.getWriter().write(jsonResponse);
            } else {
                // 获取特定学生详情
                String idStr = pathInfo.substring(1);
                try {
                    int studentId = Integer.parseInt(idStr);

                    String sql = "SELECT * FROM t_student WHERE studentId = ?";
                    pstmt = conn.prepareStatement(sql);
                    pstmt.setInt(1, studentId);
                    rs = pstmt.executeQuery();

                    if (rs.next()) {
                        Student student = new Student(
                                rs.getInt("studentId"),
                                rs.getString("name"),
                                rs.getString("dormBuildName"),
                                rs.getString("dormName"),
                                rs.getString("sex")
                        );

                        Gson gson = new Gson();
                        String jsonResponse = gson.toJson(student);
                        response.getWriter().write(jsonResponse);
                    } else {
                        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                        Gson gson = new Gson();
                        String jsonResponse = gson.toJson(new ResponseData(false, "学生未找到"));
                        response.getWriter().write(jsonResponse);
                    }
                } catch (NumberFormatException e) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    Gson gson = new Gson();
                    String jsonResponse = gson.toJson(new ResponseData(false, "无效的学生ID"));
                    response.getWriter().write(jsonResponse);
                }
            }
        } catch (Exception e) {
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        handleCors(response);
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        StringBuilder jsonBuilder = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }
        }

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            Gson gson = new Gson();
            Student newStudent = gson.fromJson(jsonBuilder.toString(), Student.class);

            String sql = "INSERT INTO t_student (name, dormBuildName, dormName, sex) VALUES (?, ?, ?, ?)";
            conn = DBUtils.getConnection();
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, newStudent.getName());
            pstmt.setObject(2, newStudent.getDormBuildName());
            pstmt.setString(3, newStudent.getDormName());
            pstmt.setString(4, newStudent.getSex());

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        newStudent.setStudentId(generatedKeys.getInt(1));
                    }
                }
                response.getWriter().write(gson.toJson(new ResponseData(true, "学生添加成功")));
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write(gson.toJson(new ResponseData(false, "添加失败")));
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Gson gson = new Gson();
            response.getWriter().write(gson.toJson(new ResponseData(false, "请求数据格式错误")));
        } finally {
            DBUtils.close(conn, pstmt, null);
        }
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        handleCors(response);
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String pathInfo = request.getPathInfo();
        if (pathInfo == null || pathInfo.equals("/")) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Gson gson = new Gson();
            response.getWriter().write(gson.toJson(new ResponseData(false, "必须指定学生ID")));
            return;
        }

        String idStr = pathInfo.substring(1);
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            int studentId = Integer.parseInt(idStr);

            StringBuilder jsonBuilder = new StringBuilder();
            try (BufferedReader reader = request.getReader()) {
                String line;
                while ((line = reader.readLine()) != null) {
                    jsonBuilder.append(line);
                }
            }

            Gson gson = new Gson();
            Student updatedStudent = gson.fromJson(jsonBuilder.toString(), Student.class);

            String sql = "UPDATE t_student SET name = ?, dormBuildName = ?, dormName = ?, sex = ? WHERE studentId = ?";
            conn = DBUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, updatedStudent.getName());
            pstmt.setString(2, updatedStudent.getDormBuildName());
            pstmt.setString(3, updatedStudent.getDormName());
            pstmt.setString(4, updatedStudent.getSex());
            pstmt.setInt(5, studentId);

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                response.getWriter().write(gson.toJson(new ResponseData(true, "学生信息更新成功")));
            } else {
            }
        } catch (NumberFormatException e) {
        } catch (Exception e) {
        }
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        handleCors(response);
        response.setContentType("application/json;charset=UTF-8");

        String pathInfo = request.getPathInfo();
        if (pathInfo == null || pathInfo.equals("/")) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Gson gson = new Gson();
            response.getWriter().write(gson.toJson(new ResponseData(false, "必须指定学生ID")));
            return;
        }

        String idStr = pathInfo.substring(1);
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            int studentId = Integer.parseInt(idStr);

            String sql = "DELETE FROM t_student WHERE studentId = ?";
            conn = DBUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, studentId);

            int affectedRows = pstmt.executeUpdate();

            Gson gson = new Gson();
            if (affectedRows > 0) {
                response.getWriter().write(gson.toJson(new ResponseData(true, "学生删除成功")));
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write(gson.toJson(new ResponseData(false, "学生未找到")));
            }
        } catch (NumberFormatException e) {
        } catch (Exception e) {
        }
    }

    @Override
    protected void doOptions(HttpServletRequest request, HttpServletResponse response) {
        handleCors(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }

    private void handleCors(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Custom-Header");
    }
}